<?php
/***
The class provide the entry to Storage , Inventory
*/
class CommonController extends Zend_Controller_Action
{
    private function setAjaxResult($result,$info){
        $this->view->assign('success',$result);
        $this->view->assign('message',$info);
    }
    private function turnToAjaxResponse(){
        $this->render('formsubmit','common',true);
    }
    public function init()
    {
        //Zend_Loader::loadClass('CustomerInfo');
    }
    /***
            It is for testing. 
            @todo Please remove it in product
          */
    public function indexAction()
    {
        $this->view->assign('title','Storage Testing');
    }
    public function listcategoryjsonAction()
    {
        Zend_Loader::loadClass('category');
        $tab = new category;
        $this->view->recs = $tab->fetchAll();
        $this->render('recs2json','common',true);
    }
    public function addupdateinventoryAction()
    {
        $request = $this->getRequest();
        $params = $request->getParams();
        Zend_Loader::loadClass('inventory');
        Zend_Loader::loadClass('Zend_Json');
        $rec = Zend_Json::decode($request->getParam('rec'), Zend_Json::TYPE_OBJECT);
        $action = $request->getParam('action');
        $tab = new Inventory;
        if($action == 'add'){
            $id = $tab->insert($rec);
        }else{
            $id = $rec->id;
            $where = $tab->getAdapter()->quoteInto('id = ?', $id);
            $a = array();
            foreach($rec as $key => $value)
            {
                $a[$key] = $value;
            }
            $tab->update($a,$where);
            $str = print_r($a);
        }
        
        if(isset($id)){
            $this->setAjaxResult("true",$str);
        }else{
            $this->setAjaxResult("false","Failed to save database");
        }
        $this->turnToAjaxResponse();
    }
    
    public function deleteinventoryAction()
    {   
        $rec = $this->getRequest()->getParam('rec');
        Zend_Loader::loadClass('Zend_Json');
        $rec = Zend_Json::decode($rec, Zend_Json::TYPE_OBJECT);
        Zend_Loader::loadClass('inventory');
        $tab = new Inventory;
        $id = $rec->id;
        $count = $tab->delete("id=$id");
        if($count == 0){
            $this->setAjaxResult("false","Deleted error");
        }else{
            $this->setAjaxResult("true","Deleted $count");
        }
        $this->render('formsubmit','common',true);
    }
        
    
}